﻿using BusinessEntity.Warning;
using learun.util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nacos.AspNetCore;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using APICommond;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using BusinessRule;
using System.IO;
using Microsoft.AspNetCore.Http;
using BusinessEntity.Assets;
using System.Dynamic;
using BusinessEntity.JGB;
using BusinessEntity.HTGLQueery;

namespace Assets.API.Controllers
{
    public class FinanceController : MvcControllerBase
    {
        private readonly INacosServerManager _serverManager;
        private readonly IHttpClientFactory _httpClientFactory;
        private static int index = 1;
        private static int p = 0;
        private static int c = 1;
        private static DataTable xtable = null;
        public FinanceController(INacosServerManager serverManager, IHttpClientFactory httpClientFactory) : base(serverManager)
        {
            _serverManager = serverManager;
            _httpClientFactory = httpClientFactory;
        }
        #region “组织机构”
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetOrg()
        {
            try
            {
                // GetUserAccount();
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                string org = await Getorg();
                if (org.Length == 12)
                {
                    org = org.Substring(0,9);
                }
                Orgs orgs = new Orgs();
                DataTable table = await BusinessRule.Warning.Waring.GetOrg("0");

                orgs.org = "";
                orgs.orgName = "全部";

                DataRow[] rws = table.Select("org='" + org + "'");

                foreach (DataRow rw in rws)
                {
                    orgs.org = Convert.ToString(rw["org"]).Trim();
                    orgs.orgName = Convert.ToString(rw["orgname"]).Trim();
                    List<Orgs> listo = new List<Orgs>();
                    DataRow[] rows = table.Select("porg='" + org + "'");

                    foreach (DataRow row in rows)
                    {
                        Orgs ors = new Orgs();
                        ors.org = Convert.ToString(row["org"]).Trim();
                        ors.orgName = Convert.ToString(row["orgname"]).Trim();
                        listo.Add(ors);
                        List<Orgs> list = new List<Orgs>();
                        DataRow[] drs = table.Select("porg='" + Convert.ToString(row["org"]).Trim() + "'");
                        foreach (DataRow dr in drs)
                        {
                            Orgs os = new Orgs();
                            os.org = Convert.ToString(dr["org"]);
                            os.orgName = Convert.ToString(dr["orgname"]);
                            list.Add(os);
                            List<Orgs> ol = new List<Orgs>();
                            DataRow[] rs = table.Select("porg='" + Convert.ToString(dr["org"]) + "'");
                            foreach (DataRow r in rs)
                            {
                                Orgs o = new Orgs();
                                o.org = Convert.ToString(r["org"]);
                                o.orgName = Convert.ToString(r["orgname"]);
                                ol.Add(o);
                            }
                            os.orgs = ol;
                        }
                        ors.orgs = list;
                    }
                    orgs.orgs = listo;
                }


                return Success(orgs, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetOrgTree(string orgname = "")
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                string org = await Getorg();
                if (org.Length == 12)
                {
                    org = org.Substring(0, 9);
                }
                Orgs orgs = new Orgs();
                DataTable table = await BusinessRule.Warning.Waring.GetOrgTree(orgname);


                DataRow[] rws = table.Select("org='" + org + "'");
                foreach (DataRow rw in rws)
                {
                    orgs.org = Convert.ToString(rw["org"]).Trim();
                    orgs.orgName = Convert.ToString(rw["orgname"]).Trim();
                    orgs.oname = Convert.ToString(rw["oname"]).Trim();
                    List<Orgs> listo = new List<Orgs>();
                    DataRow[] rows = table.Select("porg='" + org + "'");

                    foreach (DataRow row in rows)
                    {
                        Orgs ors = new Orgs();
                        ors.org = Convert.ToString(row["org"]).Trim();
                        ors.orgName = Convert.ToString(row["orgname"]).Trim();
                        ors.oname = Convert.ToString(row["oname"]).Trim();
                        listo.Add(ors);
                        List<Orgs> list = new List<Orgs>();
                        DataRow[] drs = table.Select("porg='" + Convert.ToString(row["org"]).Trim() + "'");
                        foreach (DataRow dr in drs)
                        {
                            Orgs os = new Orgs();
                            os.org = Convert.ToString(dr["org"]);
                            os.orgName = Convert.ToString(dr["orgname"]);
                            os.oname = Convert.ToString(dr["oname"]).Trim();
                            list.Add(os);
                            List<Orgs> ol = new List<Orgs>();
                            DataRow[] rs = table.Select("porg='" + Convert.ToString(dr["org"]) + "'");
                            foreach (DataRow r in rs)
                            {
                                Orgs o = new Orgs();
                                o.org = Convert.ToString(r["org"]);
                                o.orgName = Convert.ToString(r["orgname"]);
                                o.oname = Convert.ToString(r["oname"]).Trim();
                                ol.Add(o);
                            }
                            os.orgs = ol;
                        }
                        ors.orgs = list;
                    }
                    orgs.orgs = listo;
                }


                return Success(orgs);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetOrgByPorg(string org = "", string orgname = "", string lh = "", string ss = "", string zt = "", int current = 1, int size = 20)
        {
            if (string.IsNullOrEmpty(org))
            {
                org = await Getorg();
            }
            //if (org.Length == 12)
            //{
            //    org = org.Substring(0, 9);
            //}
            _logger.Log(LogLevel.Info, "GetOrgByPorg组织代码" + org);
            (DataTable, int) dataTable = await BusinessRule.Warning.Waring.GetOrgByPorg(org, orgname, lh, ss, zt, current, size);
            dataTable.Item1.Columns.Add("xh", typeof(int));
            if (xtable == null)
            {
                xtable = dataTable.Item1;
            }
            if (xtable == null)
            {
                index = 1;
            }
            else
            {
                foreach (DataRow dr in xtable.Rows)
                {
                    if (dr["xh"].ToString() != "")
                    {
                        int xh = Convert.ToInt32(dr["xh"]);
                        if (xh > index)
                        {
                            index = xh;
                        }
                    }

                }
            }

            foreach (DataRow row in dataTable.Item1.Rows)
            {
                string or = Convert.ToString(row["org"]);
                if (or.Length == 15)
                {
                    DataRow[] rows = xtable.Select("org='" + or + "'");
                    if (rows.Length > 0)
                    {
                        if (rows[0]["xh"].ToString() != "")
                        {
                            row["xh"] = rows[0]["xh"];

                        }
                        else
                        {
                            row["xh"] = index;
                            rows[0]["xh"] = index;
                            index++;
                        }
                    }
                    else
                    {
                        row["xh"] = index;
                        xtable.Rows.Add(row.ItemArray);
                        index++;
                    }



                }

            }

            Page pa = new Page();
            pa.records = dataTable.Item1;
            pa.total = dataTable.Item2;
            return Success(pa);
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetOrgsx()
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                DataTable table = await BusinessRule.Warning.Waring.GetDicInfo("orgsx");
                return Success(table, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetOrgfl()
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                DataTable table = await BusinessRule.Warning.Waring.GetDicInfo("orgfl");
                return Success(table, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetOrgzt()
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                DataTable table = await BusinessRule.Warning.Waring.GetDicInfo("orgzt");
                return Success(table, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SaveOrg(JObject org)
        {
            try
            {
                //JObject jb = JObject.Parse(org);
                await BusinessRule.Warning.Waring.SaveOrg(org);
                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail("失败" + ex.Message);
            }


        }
        #endregion 

        #region "预算"
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetBudgets(string org = "", string month = "", int current = 1, int size = 20)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs = await Getorg();
                if (org.Length == 12)
                {
                    org = org.Substring(0, 9);
                }
                if (!org.Contains(orgs))
                {
                    org = orgs;
                }


                if (org.Contains("320508"))
                {
                    if (month == null || month == "")
                    {
                        month = DateTime.Today.ToString("yyyy");
                    }
                    (DataTable, int) SelectTable = await BusinessRule.Warning.Waring.Getbugets(org, month, current, size);
                    DataTable table = SelectTable.Item1;
                    table = DateString.Dateformat(table);
                    Page pa = new Page();
                    pa.records = table;
                    pa.total = SelectTable.Item2;
                    _logger.Log(LogLevel.Info, Success(pa).ToJson());
                    return Success(pa, true);
                }
                else
                {
                    string json = await GetJavaBudgets(org, month, current, size);
                    JObject j = JObject.Parse(json);
                    if (j["code"].ToString() != "200")
                    {
                        return Fail("未获取到预算数据,Java接口返回错误信息：" + j["msg"].ToString());
                    }
                    JObject data = JObject.Parse(j["data"].ToString());
                    _logger.Log(LogLevel.Info, Success(data).ToJson());
                    return Success(data);
                }
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetBugetsInfo(string ysid, string org)
        {
            try
            {
                if (org == null || org == "")
                {
                    org = await Getorg();
                    if (org.Length == 12)
                    {
                        org = org.Substring(0, 9);
                    }
                }
                if (org.Contains("320508"))
                {
                    DataTable dataTable = await BusinessRule.Warning.Waring.GetBudgetInfo(ysid, org);
                    dataTable = DateString.Dateformat(dataTable);
                    DataTable zf = await BusinessRule.Warning.Waring.GetZFInfo(ysid);
                    zf = DateString.Dateformat(zf);
                    BugetsInfo info = new BugetsInfo();
                    info.budget = DataToEntity.DataTableToEntity<Budget>(dataTable);
                    List<ZFPZ> listp = new List<ZFPZ>();
                    listp = DataToEntity.DataTableToEntityList<ZFPZ>(zf) as List<ZFPZ>;
                    info.zfpz = listp;
                    _logger.Log(LogLevel.Info, Success(info).ToJson());
                    return Success(info, true);
                }
                else
                {
                    string json = await GetJavaBudgetsInfo(ysid);
                    JObject j = JObject.Parse(json);
                    JObject data = JObject.Parse(j["data"].ToString());
                    _logger.Log(LogLevel.Info, Success(data).ToJson());
                    return Success(data);
                }
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetBudget()
        {
            string url = ConfigHelper.GetConfig().ZB;
            string strAuthorization = GetAuthorization();
            var client = _httpClientFactory.CreateClient();
            //"Basic " +
            client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo


            //url = url.Replace("172.31.162.64:4000", "118.190.140.38:4000");
            //url = GetIpAddress(baseUrl) + permission;
            string body = "";
            if (body != "")
            {
                url = url + "?" + body;
            }
            var response = await client.GetAsync(url);

            //获取请求到数据，并转化为字符串
            var result = response.Content.ReadAsStringAsync().Result;
            JObject jb = JObject.Parse(result);
            if (jb["code"].ToString() == "200")
            {
                JArray ja = JArray.Parse(jb["data"].ToString());
                string ver = await BusinessRule.Warning.Waring.ImportBudget(ja);
                if (ver == "")
                {
                    return Success("成功");
                }
                else
                {
                    return Fail("失败" + ver);
                }
            }
            return Success("成功");
        }

        #endregion

        #region "资产"
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetAssets([FromQuery] AssetQuerry querry)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs = await Getorg();
                if (orgs.Length == 12)
                {
                    orgs = orgs.Substring(0, 9);
                }
                if (string.IsNullOrEmpty(querry.org))
                {

                    querry.org = orgs;
                }

                if (!querry.org.Contains(orgs))
                {
                    querry.org = orgs;
                }


                if (string.IsNullOrEmpty(querry.xzls) || querry.xzls=="null")
                {
                    querry.xzls = "0";
                }

                if (string.IsNullOrEmpty(querry.xzle) || querry.xzle == "null")
                {
                    querry.xzle = "0";
                }
                _logger.Log(LogLevel.Info, querry.org);
                _logger.Log(LogLevel.Info, querry.cyjg);
                (DataTable, int) SelectTable = await BusinessRule.Warning.Waring.GetAssets(querry.org, querry.type, querry.zcmc, querry.zcbm, querry.zclb, querry.zylx, querry.zcxz, querry.zt, querry.zkdm, querry.dwlx, querry.dwsx, querry.cyjg, Convert.ToDecimal(querry.xzls), Convert.ToDecimal(querry.xzle), querry.current, querry.size);
                DataTable dataTable = await BusinessRule.Warning.Waring.GetAssetsSum(querry.org, querry.type, querry.zcmc, querry.zcbm, querry.zclb, querry.zylx, querry.zcxz, querry.zt, querry.zkdm, querry.dwlx, querry.dwsx, querry.cyjg);
                DataTable table = await BusinessRule.Warning.Waring.GetWXZC(querry.org, querry.zcmc, querry.zcbm, querry.zclb, querry.zcxz, querry.zkdm, querry.dwlx, querry.dwsx);
                DataTable SelectTablex = await BusinessRule.Warning.Waring.GetAssetsX(querry.org, querry.type, querry.zcmc, querry.zcbm, querry.zclb, querry.zylx, querry.zcxz, querry.zt, querry.zkdm, querry.dwlx, querry.dwsx, querry.cyjg, Convert.ToDecimal(querry.xzls), Convert.ToDecimal(querry.xzle), querry.current, querry.size);
                _logger.Log(LogLevel.Info, querry.org + "yyyyyy");
                int count = SelectTable.Item2;
                decimal summj = 0;
                decimal sumktmj = 0;
                decimal sumyz = 0;
                decimal htsl = 0;
                decimal htje = 0;
                foreach (DataRow row in SelectTablex.Rows)
                {
                    if (querry.type == "1")
                    {
                        if (row["jzmj"] != DBNull.Value)
                        {
                            summj = summj + Convert.ToDecimal(row["jzmj"]);
                        }
                    }
                    else
                    {
                        if (row["zymj"] != DBNull.Value)
                        {
                            summj = summj + Convert.ToDecimal(row["zymj"]);
                        }
                    }
                    if (row["kymj"] != DBNull.Value)
                    {
                        sumktmj = sumktmj + Convert.ToDecimal(row["kymj"]);
                    }
                    if (row["yz"] != DBNull.Value)
                    {
                        sumyz = sumyz + Convert.ToDecimal(row["yz"]);
                    }
                    //htsl = Convert.ToDecimal(row["htsl"]);
                    //htje = Convert.ToDecimal(row["htje"]);
                }

                foreach (DataRow row in dataTable.Rows)
                {
                    htsl = Convert.ToDecimal(row["htsl"]);
                    htje = Convert.ToDecimal(row["htje"]);
                }
                decimal wyz = 0;
                foreach (DataRow row1 in table.Rows)
                {
                    wyz = wyz + Convert.ToDecimal(row1["yz"]);
                }
                AssetsSum sum = new AssetsSum();
                sum.count = count;
                sum.kymj = sumktmj;
                sum.total = count;
                sum.yz = sumyz;
                sum.zmj = summj;
                sum.htsl = htsl;
                sum.htje = htje;
                sum.wyz = wyz;
                sum.zyz = sumyz + wyz;
                List<Asset> list = new List<Asset>();
                list = DataToEntity.DataTableToEntityList<Asset>(SelectTable.Item1) as List<Asset>;
                sum.records = list;



                _logger.Log(LogLevel.Info, Success(sum).ToJson());
                return Success(sum);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetAssetsInfo(string zcbm)
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                AssetsInfo info = new AssetsInfo();
                DataTable dataTable = await BusinessRule.Warning.Waring.GetAssetsInfo(zcbm);
                DataTable zf = await BusinessRule.Warning.Waring.GetAssetsContractInfo(zcbm);
                info.asset = DataToEntity.DataTableToEntity<Asset>(dataTable);
                DataView view = zf.DefaultView;
                view.RowFilter = "htzt='当前合同'";
                List<BusinessEntity.Warning.Contract> listc = new List<BusinessEntity.Warning.Contract>();
                listc = DataToEntity.DataTableToEntityList<BusinessEntity.Warning.Contract>(view.ToTable()) as List<BusinessEntity.Warning.Contract>;
                info.contracts = listc;
                List<BusinessEntity.Warning.Contract> listh = new List<BusinessEntity.Warning.Contract>();
                DataView view1 = zf.DefaultView;
                view1.RowFilter = "htzt='历史合同'";
                listh = DataToEntity.DataTableToEntityList<BusinessEntity.Warning.Contract>(view1.ToTable()) as List<BusinessEntity.Warning.Contract>;
                info.contract_historys = listh;

                Contractsum contractsum = new Contractsum();
                DataTable htmj = await BusinessRule.Warning.Waring.GetHTMJ(zcbm);
                if (htmj.Rows.Count > 0)
                {
                    contractsum.czmj += Convert.ToDecimal(htmj.Rows[0]["tradearea"]);
                }
                if (listc != null)
                {
                    contractsum.count = listc.Count;
                    foreach (BusinessEntity.Warning.Contract c in listc)
                    {
                        // contractsum.czmj += Convert.ToDecimal(c.zlmj);
                        contractsum.zje += Convert.ToDecimal(c.ttlamt);
                    }
                }
                info.contractsum = contractsum;
                ContractsumH sumh = new ContractsumH();
                DataTable htmjh = await BusinessRule.Warning.Waring.GetHTMJW(zcbm);
                if (htmjh.Rows.Count > 0)
                {
                    sumh.czmj += Convert.ToDecimal(htmjh.Rows[0]["tradearea"]);
                }
                if (listh != null)
                {
                    sumh.count = listh.Count;
                    foreach (BusinessEntity.Warning.Contract c in listh)
                    {
                        //sumh.czmj += Convert.ToDecimal(c.zlmj);
                        sumh.zje += Convert.ToDecimal(c.ttlamt);
                    }
                }
                info.contractsum_historys = sumh;
                return Success(info);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetBuildings(string org = "", string area = "", string zcbm = "", string zcxz = "", string cjdw = "", string zcmc = "", string dwlx = "", string dwsx = "", int current = 1, int size = 20)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs = await Getorg();
                if (orgs.Length == 12)
                {
                    orgs = orgs.Substring(0, 9);
                }
                if (!org.Contains(orgs))
                {
                    org = orgs;
                }

                (DataTable, int) SelectTable = await BusinessRule.Warning.Waring.GetBuilding(org, area, zcbm, zcxz, cjdw, zcmc, dwlx, dwsx, current, size);
                DataTable table = await BusinessRule.Warning.Waring.GetBuildingSum(org, area, zcbm, zcxz, cjdw, zcmc, dwlx, dwsx);
                int count = SelectTable.Item2;
                decimal ysze = 0;
                foreach (DataRow row in table.Rows)
                {
                    ysze += Convert.ToDecimal(row["je"]);
                }

                BuildingSum sum = new BuildingSum();
                sum.count = count;
                sum.total = count;
                sum.ysze = ysze / 10000;
                List<Building> list = new List<Building>();
                list = DataToEntity.DataTableToEntityList<Building>(table) as List<Building>;
                sum.records = list;
                _logger.Log(LogLevel.Info, Success(sum).ToJson());
                return Success(sum);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetBuildingByCode(string zcbm)
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                Building buid = new Building();
                DataTable dataTable = await BusinessRule.Warning.Waring.GetBuildingByCode(zcbm);
                buid = DataToEntity.DataTableToEntity<Building>(dataTable);
                return Success(buid, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetSYZK()
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                DataTable dataTable = await BusinessRule.Warning.U8Data.GetSYZK();

                return Success(dataTable, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        #endregion

        #region "预警"
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetBugetWarn(string org = "")
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs = await Getorg();
                if (orgs.Length == 12)
                {
                    orgs = orgs.Substring(0, 9);
                }
                _logger.Log(LogLevel.Info, "返回的组织代码" + orgs);
                if (!org.Contains(orgs))
                {
                    org = orgs;
                }

                if (org == null || org == "")
                {
                    return Fail("需要参数【组织代码】");
                }
                BugetWarn warn = new BugetWarn();
                DataTable yys = await BusinessRule.Warning.Waring.GetYSS(org);
                DataTable yyys = await BusinessRule.Warning.Waring.GetYYYSS(org);
                DataTable sy = await BusinessRule.Warning.Waring.GetSYYSS(org);
                List<BusinessEntity.Warning.YS> listy = new List<BusinessEntity.Warning.YS>();
                listy = DataToEntity.DataTableToEntityList<BusinessEntity.Warning.YS>(yys) as List<BusinessEntity.Warning.YS>;
                warn.ys = listy;
                List<ZXS> listz = new List<ZXS>();
                listz = DataToEntity.DataTableToEntityList<ZXS>(yyys) as List<ZXS>;
                warn.zxs = listz;
                List<YE> liste = new List<YE>();
                liste = DataToEntity.DataTableToEntityList<YE>(sy) as List<YE>;
                warn.ye = liste;

                return Success(warn, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetContractWarn(string org = "", string year = "", string month = "", string quarter = "")
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs = await Getorg();
                if (orgs.Length == 12)
                {
                    orgs = orgs.Substring(0, 9);
                }
                if (!org.Contains(orgs))
                {
                    org = orgs;
                }

                if (org == null || org == "")
                {
                    return Fail("需要参数【组织代码】");
                }
                string endmonth = "";
                if (month == null)
                {
                    month = "";
                }
                if (year == null)
                {
                    year = "";
                }
                if (year.Trim() != "")
                {
                    month = year + "01";
                    endmonth = year + "12";
                }
                if (month.Trim() != "" && endmonth == "")
                {
                    endmonth = "";
                }

                if (month.Trim() == "" && year.Trim() == "")
                {
                    month = DateTime.Today.Year + "01";
                    endmonth = DateTime.Today.Year + "12";
                }
                //if()
                //if (month.Trim() == "")
                //{
                //    month = DateTime.Today.ToString("yyyyMM");

                //}

                if (quarter != "")
                {
                    switch (quarter)
                    {
                        case "1":
                            month = DateTime.Today.Year + "01";
                            endmonth = DateTime.Today.Year + "03";
                            break;
                        case "2":
                            month = DateTime.Today.Year + "04";
                            endmonth = DateTime.Today.Year + "06";
                            break;
                        case "3":
                            month = DateTime.Today.Year + "07";
                            endmonth = DateTime.Today.Year + "09";
                            break;
                        case "4":
                            month = DateTime.Today.Year + "10";
                            endmonth = DateTime.Today.Year + "12";
                            break;
                    }
                }
                ContractWarn warn = new ContractWarn();
                DataTable htsl = await BusinessRule.Warning.Waring.Gethtsl(org, month, endmonth);
                DataTable htzje = await BusinessRule.Warning.Waring.Gethtzje(org, month, endmonth);
                DataTable htysk = await BusinessRule.Warning.Waring.Gethtysk(org, month, endmonth);
                DataTable htyqk = await BusinessRule.Warning.Waring.Gethtyqk(org, month, endmonth);
                Info info = new Info();
                info.num = Convert.ToInt32(htsl.Rows[0][0]);
                info.zje = Convert.ToDecimal(htzje.Rows[0][0]);
                info.yje = Convert.ToDecimal(htysk.Rows[0][0]);
                info.qje = Convert.ToDecimal(htyqk.Rows[0][0]);
                warn.info = info;
                List<MonthJe> listm = new List<MonthJe>();
                DataTable htyje = await BusinessRule.Warning.Waring.Gethtyje(org, month);
                for (int i = 1; i <= 12; i++)
                {
                    DataRow[] rows = htyje.Select("month='" + i + "'");
                    if (rows.Length == 0)
                    {
                        DataRow row = htyje.NewRow();
                        row["month"] = i;
                        row["je"] = 0;
                        htyje.Rows.Add(row);
                    }
                }
                //htyje.Columns.ToInt();
                ////col.DataType = typeof(int);
                //DataView dv = htyje.DefaultView;

                //dv.Sort="month asc";
                htyje = htyje.Rows.Cast<DataRow>().OrderBy(r => int.Parse(r["month"].ToString())).CopyToDataTable();
                listm = DataToEntity.DataTableToEntityList<MonthJe>(htyje) as List<MonthJe>;
                warn.months = listm;
                List<OrgCount> listo = new List<OrgCount>();
                DataTable htysl = await BusinessRule.Warning.Waring.Gethtysl(org, month, endmonth);
                listo = DataToEntity.DataTableToEntityList<OrgCount>(htysl) as List<OrgCount>;
                warn.orgCounts = listo;
                List<OrgCQ> listq = new List<OrgCQ>();
                DataTable htcq = await BusinessRule.Warning.Waring.Gethtcq(org, month, endmonth);
                listq = DataToEntity.DataTableToEntityList<OrgCQ>(htcq) as List<OrgCQ>;

                warn.orgCQs = listq;
                DataTable htkp = await BusinessRule.Warning.Waring.Gethtkp(org);
                List<orgKP> listk = new List<orgKP>();
                listk = DataToEntity.DataTableToEntityList<orgKP>(htkp) as List<orgKP>;
                warn.orgKP = listk;

                List<orgyq> listyq = new List<orgyq>();
                DataTable htyq = await BusinessRule.Warning.Waring.Gezjyq(org);
                listyq = DataToEntity.DataTableToEntityList<orgyq>(htyq) as List<orgyq>;
                warn.orgyq = listyq;

                return Success(warn, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetFinanceWarn(string org = "", string year = "", string month = "", string quarter = "")
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs = await Getorg();
                if (orgs.Length == 12)
                {
                    orgs = orgs.Substring(0, 9);
                }
                if (!org.Contains(orgs))
                {
                    org = orgs;
                }

                if (org == null || org == "")
                {
                    return Fail("需要参数【组织代码】");
                }
                string endmonth = "";

                if (string.IsNullOrEmpty(month))
                {
                    month = "";
                }
                else
                {
                    if (month.Contains("月"))
                    {
                        month = month.Substring(0, month.LastIndexOf("月"));
                        if (month.Length == 1)
                        {
                            month = "0" + month;
                        }
                    }
                }
                if (year == null)
                {
                    year = "";
                }
                if (year.Trim() != "")
                {
                    if (string.IsNullOrEmpty(month))
                    {
                        month = year + "01";
                    }
                    else
                    {
                        month = year + month;
                    }
                    endmonth = year + "12";
                }
                //if (month.Trim() != "")
                //{
                //    month = month.Replace("-", "");
                //    endmonth = "";
                //}
                if (month.Trim() == "" && year.Trim() == "")
                {
                    if (DateTime.Today.Day > 15)
                    {
                        month = DateTime.Today.AddMonths(-1).ToString("yyyyMM");
                        endmonth = DateTime.Today.AddMonths(-1).ToString("yyyyMM");
                    }
                    else
                    {
                        month = DateTime.Today.AddMonths(-2).ToString("yyyyMM");
                        endmonth = DateTime.Today.AddMonths(-2).ToString("yyyyMM");
                    }
                }

                if (quarter != "")
                {
                    switch (quarter)
                    {
                        case "1":
                            month = DateTime.Today.Year + "01";
                            endmonth = DateTime.Today.Year + "03";
                            break;
                        case "2":
                            month = DateTime.Today.Year + "04";
                            endmonth = DateTime.Today.Year + "06";
                            break;
                        case "3":
                            month = DateTime.Today.Year + "07";
                            endmonth = DateTime.Today.Year + "09";
                            break;
                        case "4":
                            month = DateTime.Today.Year + "10";
                            endmonth = DateTime.Today.Year + "12";
                            break;
                    }
                }
                FinanceWarn warn = new FinanceWarn();
                FinanceInfo info = new FinanceInfo();
                DataTable ye = await BusinessRule.Warning.Waring.GetYE(org, month, endmonth);
                DataTable zsz = await BusinessRule.Warning.Waring.GetZSZ(org, month, endmonth);
                info.ye = Convert.ToDecimal(ye.Rows[0][0]);
                info.zsr = Convert.ToDecimal(zsz.Rows[0]["zsr"]);
                info.zzc = Convert.ToDecimal(zsz.Rows[0]["zzc"]);
                warn.info = info;
                List<SRPH> lists = new List<SRPH>();
                DataTable srph = await BusinessRule.Warning.Waring.GetSRPH(org, month, endmonth);
                lists = DataToEntity.DataTableToEntityList<SRPH>(srph) as List<SRPH>;
                warn.srph = lists;
                List<ZCJGInfo> listzc = new List<ZCJGInfo>();
                DataTable zcjg = await BusinessRule.Warning.Waring.GetZCJG(org, month, endmonth);
                ZCJGInfo z = new ZCJGInfo();
                z.value = Convert.ToDecimal(zcjg.Rows[0]["jy"]);
                z.name = "经营支出";
                z.color = "#4E6FCC";
                listzc.Add(z);

                ZCJGInfo zc = new ZCJGInfo();
                zc.value = Convert.ToDecimal(zcjg.Rows[0]["gl"]);
                zc.name = "管理费支出";
                zc.color = "#FFC73A";
                listzc.Add(zc);

                warn.zcjg = listzc;
                List<YEPH> listy = new List<YEPH>();
                DataTable yeph = await BusinessRule.Warning.Waring.GetYEPH(org, month, endmonth);
                listy = DataToEntity.DataTableToEntityList<YEPH>(yeph) as List<YEPH>;
                warn.yeph = listy;
                List<ZCQS> listz = new List<ZCQS>();
                DataTable zcqs = await BusinessRule.Warning.Waring.GetZCQS(org, month);
                listz = DataToEntity.DataTableToEntityList<ZCQS>(zcqs) as List<ZCQS>;
                warn.zcqs = listz;
                List<SRJGInfo> sr = new List<SRJGInfo>();
                DataTable srjg = await BusinessRule.Warning.Waring.GetSRJG(org, month, endmonth);
                SRJGInfo s = new SRJGInfo();
                s.value = Convert.ToDecimal(srjg.Rows[0]["jy"]);
                s.name = "经营收入";
                s.color = "#4E6FCC";
                sr.Add(s);

                SRJGInfo fb = new SRJGInfo();
                fb.value = Convert.ToDecimal(srjg.Rows[0]["fb"]);
                fb.name = "发包及上交收入";
                fb.color = "#FFC73A";
                sr.Add(fb);

                SRJGInfo bz = new SRJGInfo();
                bz.value = Convert.ToDecimal(srjg.Rows[0]["bz"]);
                bz.name = "补助收入";
                bz.color = "#8AE373";
                sr.Add(bz);

                SRJGInfo qt = new SRJGInfo();
                qt.value = Convert.ToDecimal(srjg.Rows[0]["qt"]);
                qt.name = "其他收入";
                qt.color = "#57C2E2";
                sr.Add(qt);

                SRJGInfo tz = new SRJGInfo();
                tz.value = Convert.ToDecimal(srjg.Rows[0]["tz"]);
                tz.name = "投资收入";
                tz.color = "#FF7C43";
                sr.Add(tz);

                warn.srjg = sr;

                return Success(warn, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetFinancex(string org = "", string month = "")
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs = await Getorg();
                if (orgs.Length == 12)
                {
                    orgs = orgs.Substring(0, 9);
                }
                if (!org.Contains(orgs))
                {
                    org = orgs;
                }

                if (month == null || month.Trim() == "")
                {
                    month = DateTime.Today.AddMonths(-2).ToString("yyyyMM");
                }
                if (month.Contains("-"))
                {
                    month = month.Replace("-", "");
                }

                Financex financex = new Financex();
                List<SRPH> lists = new List<SRPH>();
                DataTable srph = await BusinessRule.Warning.Waring.GetSRPHx(org, month);
                lists = DataToEntity.DataTableToEntityList<SRPH>(srph) as List<SRPH>;
                financex.srph = lists;
                List<ZCPH> listz = new List<ZCPH>();
                DataTable zcph = await BusinessRule.Warning.Waring.GetZCPHx(org, month);
                listz = DataToEntity.DataTableToEntityList<ZCPH>(zcph) as List<ZCPH>;
                financex.zcph = listz;
                List<KMYEPH> listk = new List<KMYEPH>();
                DataTable knye = await BusinessRule.Warning.Waring.GetZCFZPHx(org, month);
                listk = DataToEntity.DataTableToEntityList<KMYEPH>(knye) as List<KMYEPH>;
                financex.kmyeph = listk;
                List<ZCFZPH> listf = new List<ZCFZPH>();
                DataTable zcfz = await BusinessRule.Warning.Waring.GetZCFZPHx1(org, month);
                listf = DataToEntity.DataTableToEntityList<ZCFZPH>(zcfz) as List<ZCFZPH>;
                financex.zcfzph = listf;
                List<SYFPPH> listy = new List<SYFPPH>();
                DataTable syfp = await BusinessRule.Warning.Waring.GetZCFZPHx2(org, month);
                listy = DataToEntity.DataTableToEntityList<SYFPPH>(syfp) as List<SYFPPH>;
                financex.syfpph = listy;
                List<ZWZQPH> listw = new List<ZWZQPH>();
                DataTable zqzw = await BusinessRule.Warning.Waring.GetZWZQPHx(org, month);
                listw = DataToEntity.DataTableToEntityList<ZWZQPH>(zqzw) as List<ZWZQPH>;
                financex.zwzqph = listw;

                return Success(financex, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetWarning(string org = "", string month = "")
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs1 = await Getorg();
                if (orgs1.Length == 12)
                {
                    orgs1 = orgs1.Substring(0, 9);
                }
                if (!org.Contains(orgs1))
                {
                    org = orgs1;
                }

                if (org == null || org == "")
                {
                    return Fail("需要参数【组织代码】");
                }
                _logger.Log(LogLevel.Info, DateTime.Now + "会计期间" + month);
                if (month == null || month.Trim() == "")
                {
                    month = DateTime.Today.ToString("yyyyMM");
                }
                else
                {
                    if (month.Contains("-"))
                    {
                        month = month.Replace("-", "");
                    }
                }
                string mm= DateTime.Today.AddMonths(-1).ToString("yyyyMM");
                if (DateTime.Today.Day < 15)
                { 
                mm = DateTime.Today.AddMonths(-2).ToString("yyyyMM");
                }
                _logger.Log(LogLevel.Info, DateTime.Now + "会计期间"+month);
                Warning warning = new Warning();

                string listorg = "";
                string name = "";
                _logger.Log(LogLevel.Info, DateTime.Now + "开始组织单位");
                Orgs orgs = new Orgs();
                DataTable table = await BusinessRule.Warning.Waring.GetOrg("0");
                DataRow[] rws = table.Select("org='" + org + "'");
                foreach (DataRow rw in rws)
                {
                    orgs.org = Convert.ToString(rw["org"]).Trim();
                    orgs.orgName = Convert.ToString(rw["orgname"]).Trim();
                    name = Convert.ToString(rw["orgname"]).Trim();
                    listorg += "\"" + Convert.ToString(rw["org"]).Trim() + "\",";
                    List<Orgs> listo = new List<Orgs>();
                    DataRow[] rows = table.Select("porg='" + org + "'");

                    foreach (DataRow row in rows)
                    {
                        Orgs ors = new Orgs();
                        ors.org = Convert.ToString(row["org"]).Trim();
                        ors.orgName = Convert.ToString(row["orgname"]).Trim();
                        listorg += "\"" + Convert.ToString(row["org"]).Trim() + "\",";
                        listo.Add(ors);
                        List<Orgs> list = new List<Orgs>();
                        DataRow[] drs = table.Select("porg='" + Convert.ToString(row["org"]).Trim() + "'");
                        foreach (DataRow dr in drs)
                        {
                            Orgs os = new Orgs();
                            os.org = Convert.ToString(dr["org"]);
                            os.orgName = Convert.ToString(dr["orgname"]);
                            listorg += "\"" + Convert.ToString(dr["org"]).Trim() + "\",";
                            list.Add(os);
                            List<Orgs> ol = new List<Orgs>();
                            DataRow[] rs = table.Select("porg='" + Convert.ToString(dr["org"]) + "'");
                            foreach (DataRow r in rs)
                            {
                                Orgs o = new Orgs();
                                o.org = Convert.ToString(r["org"]);
                                o.orgName = Convert.ToString(r["orgname"]);
                                listorg += "\"" + Convert.ToString(r["org"]).Trim() + "\",";
                                ol.Add(o);
                            }
                            os.orgs = ol;
                        }
                        ors.orgs = list;
                    }
                    orgs.orgs = listo;
                }
                if (listorg != "")
                {
                    listorg = listorg.Substring(0, listorg.Length - 1);
                }
                warning.orgs = orgs;
                _logger.Log(LogLevel.Info, DateTime.Now + "结束组织单位");
                _logger.Log(LogLevel.Info, DateTime.Now + "开始获取单位数量");
                DataTable orgcount = await BusinessRule.Warning.Waring.GetOrgCount(org);
                OrgCountx ocount = new OrgCountx();
                ocount = DataToEntity.DataTableToEntity<OrgCountx>(orgcount);
                warning.orgcount = ocount;
                _logger.Log(LogLevel.Info, DateTime.Now + "结束获取单位数量");
                //DataTable zcyz = await BusinessRule.Warning.Waring.GetzcyzPHx(org, month);
                //List<AssetWarn> lista = new List<AssetWarn>();
                //lista = DataToEntity.DataTableToEntityList<AssetWarn>(zcyz) as List<AssetWarn>;
                //warning.assetWarn = lista;
                _logger.Log(LogLevel.Info, DateTime.Now + "开始固定资产结构");
                List<GDZCJG> listg = new List<GDZCJG>();
                DataTable gdzc = await BusinessRule.Warning.Waring.GetGDZCJG(org, month);
                if (gdzc.Rows.Count > 0)
                {
                    DataRow row = gdzc.Rows[0];
                    GDZCJG g = new GDZCJG();
                    g.value = Convert.ToDecimal(row["fw"]);
                    g.name = "房屋及建筑物";
                    listg.Add(g);

                    GDZCJG gd = new GDZCJG();
                    gd.value = Convert.ToDecimal(row["qt"]);
                    gd.name = "其他类资产";
                    listg.Add(gd);
                }
                warning.gdzc = listg;
                _logger.Log(LogLevel.Info, DateTime.Now + "结束固定资产结构");
                _logger.Log(LogLevel.Info, DateTime.Now + "开始资源资产结构");
                DataTable zyzc = await BusinessRule.Warning.Waring.GetZYZCJG(org, month);
                List<ZYZCJG> listzyzc = new List<ZYZCJG>();
                listzyzc = DataToEntity.DataTableToEntityList<ZYZCJG>(zyzc) as List<ZYZCJG>;
                warning.zyzc = listzyzc;
                _logger.Log(LogLevel.Info, DateTime.Now + "结束固定资产结构");
                _logger.Log(LogLevel.Info, DateTime.Now + "开始合同数量排行");
                List<Contractnum> listn = new List<Contractnum>();
                DataTable htsl = await BusinessRule.Warning.Waring.GethtslPHx(org, month);
                listn = DataToEntity.DataTableToEntityList<Contractnum>(htsl) as List<Contractnum>;
                warning.contractnum = listn;
                _logger.Log(LogLevel.Info, DateTime.Now + "结束合同数量排行");
                _logger.Log(LogLevel.Info, DateTime.Now + "开始合同金额排行");
                List<ContractMoney> listm = new List<ContractMoney>();
                DataTable htje = await BusinessRule.Warning.Waring.GethtjePHx(org, month);
                listm = DataToEntity.DataTableToEntityList<ContractMoney>(htje) as List<ContractMoney>;
                warning.contractMoney = listm;
                _logger.Log(LogLevel.Info, DateTime.Now + "结束合同金额排行");
                _logger.Log(LogLevel.Info, DateTime.Now + "开始资产数量排行");
                DataTable zsc = await BusinessRule.Warning.Waring.Getzsc(org, mm);
                warning.sum = DataToEntity.DataTableToEntity<Sum>(zsc);
                _logger.Log(LogLevel.Info, DateTime.Now + "结束资产数量排行");
                _logger.Log(LogLevel.Info, DateTime.Now + "开始收入结构排行");
                List<SRJGX> listi = new List<SRJGX>();
                DataTable srph = await BusinessRule.Warning.Waring.GetSRJGx(org, mm);
                listi = DataToEntity.DataTableToEntityList<SRJGX>(srph) as List<SRJGX>;
                warning.INCOMETOTAL = listi;
                _logger.Log(LogLevel.Info, DateTime.Now + "结束收入结构排行");
                _logger.Log(LogLevel.Info, DateTime.Now + "开始资产结构排行");
                List<ZCJGX> lists = new List<ZCJGX>();
                DataTable zcph = await BusinessRule.Warning.Waring.GetZCJGx(org, mm);
                lists = DataToEntity.DataTableToEntityList<ZCJGX>(zcph) as List<ZCJGX>;
                warning.SPENDINGTOTAL = lists;
                _logger.Log(LogLevel.Info, DateTime.Now + "结束资产结构排行");
                _logger.Log(LogLevel.Info, DateTime.Now + "开始凭证结构排行");
                DataTable pzph = await BusinessRule.Warning.Waring.GetPZPH(org, mm);
                List<PZPH> lpzph = new List<PZPH>();
                lpzph = DataToEntity.DataTableToEntityList<PZPH>(pzph) as List<PZPH>;
                warning.pzph = lpzph;
                _logger.Log(LogLevel.Info, DateTime.Now + "结束凭证结构排行");

                List<ZC> zclist = new List<ZC>();
                ZC zl = new ZC();
                zl.classname = "经营性支出";
                List<zclx> jzclx = new List<zclx>();
                ZC c = new ZC();
                c.classname = "管理支出";
                List<zclx> gzclx = new List<zclx>();
                foreach (DataRow row in zcph.Rows)
                {
                    zclx jz = new zclx();
                    jz.org = Convert.ToString(row["org"]);
                    jz.orgname= Convert.ToString(row["orgname"]);
                    jz.je= Convert.ToDecimal(row["jy"]);
                    jzclx.Add(jz);
                    zclx g = new zclx();
                    g.org = Convert.ToString(row["org"]);
                    g.orgname = Convert.ToString(row["orgname"]);
                    g.je = Convert.ToDecimal(row["gl"]);
                    gzclx.Add(g);
                }
                zl.zclb = jzclx;
                c.zclb = gzclx;
                zclist.Add(zl);
                zclist.Add(c);
                warning.zclist=zclist;
                //Warn war = new Warn();
                //DataTable xz = await BusinessRule.Warning.Waring.Getxz(org, month);
                //war.xzzc = Convert.ToInt32(xz.Rows[0][0]);
                //DataTable jg = await BusinessRule.Warning.Waring.Getjg(org, month);
                //war.zcjg = Convert.ToInt32(jg.Rows[0][0]);
                //DataTable dqht = await BusinessRule.Warning.Waring.Getdqht(org, month);
                //war.htdq = Convert.ToInt32(dqht.Rows[0][0]);
                //DataTable zccb = await BusinessRule.Warning.Waring.Getzccb(org, month);
                //war.zccb = Convert.ToInt32(zccb.Rows[0][0]);
                //DataTable ccht = await BusinessRule.Warning.Waring.Getccht(org, month);
                //war.ccht = Convert.ToInt32(ccht.Rows[0][0]);
                //DataTable cys = await BusinessRule.Warning.Waring.Getcys(org, month);
                //war.cys = Convert.ToInt32(cys.Rows[0][0]);
                //DataTable zjwdq = await BusinessRule.Warning.Waring.Getzjwdq(org, month);
                //war.zjwd = Convert.ToInt32(zjwdq.Rows[0][0]);
                //warning.warn = war;
                // List<JavaWarning> ja = new List<JavaWarning>();
                //string json = GetJavaWarning();
                //JObject jb = JObject.Parse(json);
                //if (jb["code"].ToString() == "200")
                //{
                //    ja = ExtensionsJson.ToList<JavaWarning>(jb["data"].ToString());
                //}
                _logger.Log(LogLevel.Info, DateTime.Now + "开始预警数据");
                List<JavaWarning> ja = new List<JavaWarning>();
                string url = ConfigHelper.GetConfig().ICWarning;
                string strAuthorization = GetAuthorization();
                var client = _httpClientFactory.CreateClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


                client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo

                string body = "{\"unitCodeList\":[" + listorg + "]}";
                JObject j = JObject.Parse(body);
                HttpContent httpContent = new JsonContent(j);
                string result = "";
                HttpResponseMessage response = client.PostAsync(ConfigHelper.GetConfig().ICWarning, httpContent).Result;
                if (response.IsSuccessStatusCode)
                {
                    Task<string> t = response.Content.ReadAsStringAsync();
                    if (t != null)
                    {
                        result = t.Result;
                        _logger.Log(LogLevel.Info, DateTime.Now + "预警数据" + result);
                        JObject j1 = JObject.Parse(t.Result);
                        if (j1["code"].ToString() == "200")
                        {
                            ja = ExtensionsJson.ToList<JavaWarning>(j1["data"].ToString());
                        }

                    }
                }

                warning.javaWarning = ja;
                _logger.Log(LogLevel.Info, DateTime.Now + "结束预警数据");
                _logger.Log(LogLevel.Info, DateTime.Now + "开始余额数据");
                string ye = ConfigHelper.GetConfig().YE;

                var client1 = _httpClientFactory.CreateClient();
                //"Basic " +
                client1.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo


                //url = url.Replace("172.31.162.64:4000", "118.190.140.38:4000");
                //url = GetIpAddress(baseUrl) + permission;
                string body1 = "";

                body1 = "code=" + org;

                if (body1 != "")
                {
                    ye = ye + "?" + body1;
                }
                var response1 = await client1.GetAsync(ye);

                //获取请求到数据，并转化为字符串
                var result1 = response1.Content.ReadAsStringAsync().Result;

                _logger.Log(LogLevel.Info, DateTime.Now + "余额数据" + result1);

                if (result1 != "")
                {
                    JObject jb = JObject.Parse(result1);
                    if (jb["code"].ToString() == "200")
                    {
                        JObject jx = JObject.Parse(jb["data"].ToString());
                        warning.sum.sumAmount = Convert.ToDecimal(jx["sumAmount"]);
                    }
                    else
                    {
                        warning.sum.sumAmount = warning.sum.INCOME_TOTAL - warning.sum.SPENDING_TOTAL;
                        //warning.sum.sumAmount =0;
                    }
                }
                _logger.Log(LogLevel.Info, DateTime.Now + "结束余额数据");
                _logger.Log(LogLevel.Info, DateTime.Now + "开始支出数据");
                if (org.Contains("320571"))
                {
                    string json = await GetJavaZC(org);
                    JObject zc = JObject.Parse(json);

                    if (zc["code"].ToString() != "200")
                    {
                        return Fail("未获取到支出数据,Java接口返回错误信息：" + zc["msg"].ToString());
                    }
                    JArray data = JArray.Parse(zc["data"].ToString());

                    List<ZC> listz = new List<ZC>();
                    foreach (JObject o in data)
                    {

                        ZC z = new ZC();
                        z.classname = o["className"].ToString();
                        JArray jr = JArray.Parse(o["zclb"].ToString());
                        List<zclx> listlx = new List<zclx>();
                        foreach (JObject t in jr)
                        {
                            zclx l = new zclx();
                            l.org = t["org"].ToString();
                            l.orgname = t["orgName"].ToString();
                            l.je = Convert.ToDecimal(t["je"]);
                            listlx.Add(l);
                        }
                        z.zclb = listlx;
                        listz.Add(z);
                    }
                    warning.listzc = listz;
                    _logger.Log(LogLevel.Info, DateTime.Now + "结束支出数据");
                }
                return Success(warning, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetAssetsWarn(string org = "")
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs = await Getorg();
                if (orgs.Length == 12)
                {
                    orgs = orgs.Substring(0, 9);
                }
                if (!org.Contains(orgs))
                {
                    org = orgs;
                }

                if (org == null || org == "")
                {
                    return Fail("需要参数【组织代码】");
                }

                AssetWarnInfo warn = new AssetWarnInfo();
                DataTable gdzcph = await BusinessRule.Warning.Waring.GetGDZCPH(org);
                List<GDZCPH> listg = new List<GDZCPH>();
                listg = DataToEntity.DataTableToEntityList<GDZCPH>(gdzcph) as List<GDZCPH>;
                warn.gdzcph = listg;

                DataTable jygdzcph = await BusinessRule.Warning.Waring.GetJYGDZCPH(org);
                List<JYGDZCPH> listj = new List<JYGDZCPH>();
                listj = DataToEntity.DataTableToEntityList<JYGDZCPH>(jygdzcph) as List<JYGDZCPH>;
                warn.jygdzcph = listj;

                DataTable gdzcqs = await BusinessRule.Warning.Waring.GetGDZCQS(org);
                List<GDZCQS> listd = new List<GDZCQS>();
                for (int i = 1; i <= 12; i++)
                {
                    DataRow[] rows = gdzcqs.Select("month='" + i + "'");
                    if (rows.Length == 0)
                    {
                        DataRow row = gdzcqs.NewRow();
                        row["month"] = i;
                        row["jyx"] = 0;
                        row["fjyx"] = 0;
                        gdzcqs.Rows.Add(row);
                    }
                }
                //htyje.Columns.ToInt();
                ////col.DataType = typeof(int);
                //DataView dv = htyje.DefaultView;

                //dv.Sort="month asc";
                gdzcqs = gdzcqs.Rows.Cast<DataRow>().OrderBy(r => int.Parse(r["month"].ToString())).CopyToDataTable();
                listd = DataToEntity.DataTableToEntityList<GDZCQS>(gdzcqs) as List<GDZCQS>;
                warn.gdzcqs = listd;

                DataTable zyzcqs = await BusinessRule.Warning.Waring.GetZYZCQS(org);
                List<ZYZCQS> listz = new List<ZYZCQS>();
                for (int i = 1; i <= 12; i++)
                {
                    DataRow[] rows = zyzcqs.Select("month='" + i + "'");
                    if (rows.Length == 0)
                    {
                        DataRow row = zyzcqs.NewRow();
                        row["month"] = i;
                        row["jyx"] = 0;
                        row["fjyx"] = 0;
                        zyzcqs.Rows.Add(row);
                    }
                }
                zyzcqs = zyzcqs.Rows.Cast<DataRow>().OrderBy(r => int.Parse(r["month"].ToString())).CopyToDataTable();
                listz = DataToEntity.DataTableToEntityList<ZYZCQS>(zyzcqs) as List<ZYZCQS>;
                warn.zyzcqs = listz;

                DataTable zyzcsj = await BusinessRule.Warning.Waring.GetZYZCSJ(org);
                List<ZYZCSJ> listy = new List<ZYZCSJ>();
                listy = DataToEntity.DataTableToEntityList<ZYZCSJ>(zyzcsj) as List<ZYZCSJ>;
                warn.zyzcsj = listy;

                DataTable zyzcph = await BusinessRule.Warning.Waring.GetZYZCPH(org);
                List<ZYZCPH> listh = new List<ZYZCPH>();
                listh = DataToEntity.DataTableToEntityList<ZYZCPH>(zyzcph) as List<ZYZCPH>;
                warn.zyzcph = listh;

                return Success(warn, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        #endregion

        #region  "财务凭证"
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetPZML(string org = "", string month = "", string endmont = "", string sflh = "", string ss = "", int current = 1, int size = 20)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs = await Getorg();
                if (orgs.Length == 12)
                {
                    orgs = orgs.Substring(0, 9);
                }
                if (!org.Contains(orgs))
                {
                    org = orgs;
                }

                if (month == null || month.Trim() == "")
                {
                    month = DateTime.Today.AddMonths(-2).ToString("yyyyMM");
                }
                (DataTable, int) SelectTable = await BusinessRule.Warning.Waring.GetPZML(org, month, endmont, ss, sflh, current, size);

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;

                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetPZInfo(string idpzh)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                PZInfocs info = new PZInfocs();
                DataTable ml = await BusinessRule.Warning.Waring.GetPZMLInfo(idpzh);
                info.pzml = DataToEntity.DataTableToEntity<PZML>(ml);
                List<pznrx> list = new List<pznrx>();
                DataTable nr = await BusinessRule.Warning.Waring.GetPZNRInfo(idpzh);
                list = DataToEntity.DataTableToEntityList<pznrx>(nr) as List<pznrx>;
                info.pznr = list;
                return Success(info, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetPZ(string org = "", string month = "", int current = 1, int size = 20)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                if (month == "")
                {
                    month = DateTime.Today.ToString("yyyyMM");
                }
                (DataTable, int) SelectTable = await BusinessRule.Warning.Waring.GetPZ(org, month, current, size);

                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;

                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        #endregion

        #region "合同"
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetContracts([FromQuery] HTQuerry querry)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                //string orgs = await Getorg();
                string orgs = await Getorg();
                if (orgs.Length == 12)
                {
                    orgs = orgs.Substring(0, 9);
                }
                if (string.IsNullOrWhiteSpace(querry.org))
                {

                    querry.org = orgs;
                }

                if (!querry.org.Contains(orgs))
                {
                    querry.org = orgs;
                }

                _logger.Log(LogLevel.Info, querry.org);
                ContractSum sum = new ContractSum();

                (DataTable, int) SelectTable = await BusinessRule.Warning.Waring.GetContract(querry.org, querry.start, querry.end, querry.contractcode, querry.contractname, querry.htzt, querry.sfskjh, querry.yhtbh, querry.ss, querry.sflh, querry.current, querry.size);
                DataTable table = await BusinessRule.Warning.Waring.GetContractSum(querry.org, querry.start, querry.end, querry.contractcode, querry.contractname, querry.htzt, querry.sfskjh, querry.yhtbh, querry.ss, querry.sflh);
                //sum = DataToEntity.DataTableToEntity<ContractSum>(table);
                sum.total = SelectTable.Item2;
                sum.count = SelectTable.Item2;
                foreach (DataRow row in table.Rows)
                {
                    sum.zzj = Convert.ToDecimal(row["ttlamt"]);
                    sum.zlmj = Convert.ToDecimal(row["zlmj"]);
                    sum.zcsl = Convert.ToDecimal(row["zcsl"]);
                    sum.zcyz = Convert.ToDecimal(row["zcyz"]);
                }
                List<BusinessEntity.Warning.Contract> contracts = new List<BusinessEntity.Warning.Contract>();
                contracts = DataToEntity.DataTableToEntityList<BusinessEntity.Warning.Contract>(SelectTable.Item1) as List<BusinessEntity.Warning.Contract>;
                sum.records = contracts;
                //Page pa = new Page();
                //pa.records = SelectTable.Item1;
                //pa.total = SelectTable.Item2;

                //_logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(sum);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetContractInfo(string projectCode)
        {
            try
            {
                DataTable dataTable = await BusinessRule.Warning.Waring.GetContractInfo(projectCode);

                ContractInfo info = new ContractInfo();

                info.contract = DataToEntity.DataTableToEntity<BusinessEntity.Warning.Contract>(dataTable);
                List<BusinessEntity.Warning.Assets> lista = new List<BusinessEntity.Warning.Assets>();
                DataTable zc = await BusinessRule.Warning.Waring.GetContractAssetsInfo(projectCode);

                lista = DataToEntity.DataTableToEntityList<BusinessEntity.Warning.Assets>(zc) as List<BusinessEntity.Warning.Assets>;
                info.assets = lista;
                List<ContractFile> files = new List<ContractFile>();
                DataTable f = await BusinessRule.Warning.Waring.GetContractFileInfo(projectCode);
                files = DataToEntity.DataTableToEntityList<ContractFile>(f) as List<ContractFile>;
                info.contractfile = files;
                List<ContractPlan> listp = new List<ContractPlan>();
                DataTable p = await BusinessRule.Warning.Waring.GetContractPlan(projectCode);
                listp = DataToEntity.DataTableToEntityList<ContractPlan>(p) as List<ContractPlan>;
                info.contractplans = listp;
                return Success(info);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetContractPlan(string projectCode)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                DataTable SelectTable = await BusinessRule.Warning.Waring.GetContractPlan(projectCode);


                return Success(SelectTable, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetContractPlanInfo(string id)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                DataTable SelectTable = await BusinessRule.Warning.Waring.GetContractPlanInfo(id);


                return Success(SelectTable, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> UpdateContract(JObject str)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                await BusinessRule.Warning.Waring.UpdateContract(str["prjcode"].ToString(), str["yhtbh"].ToString(), str["bz"].ToString());


                return Success("成功！");
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取欠缴情况分页
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpGet]
        // [AllowAnonymous]
        public async Task<IActionResult> getReportQJ([FromQuery] reportQj entity)
        {
            try
            {
                //_logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                //entity.UserID = GetUserId();
                //entity.DepartID = await GetDepId("contract_permission");
                string orgs = await Getorg();
                if (string.IsNullOrEmpty(entity.org))
                {
                    entity.org = orgs;
                }
                if (!entity.org.Contains(orgs))
                {
                    entity.org = orgs;
                }

                if (entity.org == null || entity.org == "")
                {
                    return Fail("需要参数【组织代码】");
                }
                if (entity.SortString == "ListID")
                {
                    entity.SortString = "djbh";
                }
                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Warning.Waring.GetQJ(entity);

                _logger.Log(LogLevel.Info, "11111" + SelectTable.ToJson());




                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取欠缴情况分页
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpGet]
        // [AllowAnonymous]
        public async Task<IActionResult> getReportQJyq([FromQuery] reportQj entity)
        {
            try
            {
                //_logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                //entity.UserID = GetUserId();
                //entity.DepartID = await GetDepId("contract_permission");
                string orgs = await Getorg();
                if (string.IsNullOrEmpty(entity.org))
                {
                    entity.org = orgs;
                }
                if (!entity.org.Contains(orgs))
                {
                    entity.org = orgs;
                }

                if (entity.org == null || entity.org == "")
                {
                    return Fail("需要参数【组织代码】");
                }
                if (entity.SortString == "ListID")
                {
                    entity.SortString = "djbh";
                }
                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Warning.Waring.GetQJyq(entity);

                _logger.Log(LogLevel.Info, "11111" + SelectTable.ToJson());




                Page pa = new Page();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        #endregion

        #region  "支付凭证"
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> ImportZF(string month = "")
        {
            string url = ConfigHelper.GetConfig().ZF;
            string strAuthorization = GetAuthorization();
            var client = _httpClientFactory.CreateClient();
            //"Basic " +
            client.DefaultRequestHeaders.Add("Authorization", "bearer " + strAuthorization);//"Basic " + clientInfo

            string body = "yearMonth=";
            if (month != "")
            {
                body += month;
            }
            else
            {
                body += DateTime.Today.ToString("yyyyMM");
            }
            if (body != "")
            {
                url = url + "?" + body;
            }
            var response = await client.GetAsync(url);

            //获取请求到数据，并转化为字符串
            var result = response.Content.ReadAsStringAsync().Result;




            JObject jb = JObject.Parse(result);
            if (jb["code"].ToString() == "200")
            {
                JArray ja = JArray.Parse(jb["data"].ToString());
                string ver = await BusinessRule.Warning.Waring.ImportZF(ja);
                if (ver == "")
                {
                    return Success("成功");
                }
                else
                {
                    return Fail("失败" + ver);
                }
            }


            return Success("成功");
        }


        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetZFPZ(string org = "", string zclxmc = "", string zjxzmc = "", string start = "", string end = "", int current = 1, int size = 20)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs = await Getorg();
                if (orgs.Length == 12)
                {
                    orgs = orgs.Substring(0, 9);
                }
                if (!org.Contains(orgs))
                {
                    org = orgs;
                }
                _logger.Log(LogLevel.Info, "单位代码" + org);
                if (org.Contains("320508"))
                {
                    if (start == null || start.Trim() == "")
                    {
                        start = DateTime.Today.Year + "0101";
                    }
                    if (end == null || end.Trim() == "")
                    {
                        end = DateTime.Today.Year + "1231";
                    }
                    (DataTable, int) SelectTable = await BusinessRule.Warning.Waring.GetZFPZ(org, zclxmc, zjxzmc, start.Replace("-", ""), end.Replace("-", ""), current, size);
                    DataTable table = SelectTable.Item1;
                    table = DateString.Dateformat(table);
                    Page pa = new Page();
                    pa.records = table;
                    pa.total = SelectTable.Item2;

                    _logger.Log(LogLevel.Info, Success(pa).ToJson());
                    return Success(pa, true);
                }
                else
                {
                    string json = await GetJavaPZ("", "", org, start, end, current, size);
                    JObject j = JObject.Parse(json);
                    if (j["code"].ToString() != "200")
                    {
                        return Fail("未获取到支出数据,Java接口返回错误信息：" + j["msg"].ToString());
                    }
                    JObject data = JObject.Parse(j["data"].ToString());
                    _logger.Log(LogLevel.Info, Success(data).ToJson());
                    return Success(data);
                }
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetZFPZInfo(string djbh, string org)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                if (org != null)
                {
                    if (org.Length > 12)
                    {
                        org = org.Substring(0, 12);
                    }
                }
                else
                {
                    org = await Getorg();
                }
                if (djbh.Contains("320508"))
                {
                    org = djbh.Substring(0, 15);
                    djbh = djbh.Substring(15);
                }
                if (org.Contains("320508"))
                {
                    ZFPZInfo info = new ZFPZInfo();
                    DataTable SelectTable = await BusinessRule.Warning.Waring.GetZFPZInfo(djbh,org);
                    SelectTable = DateString.Dateformat(SelectTable);
                    info.zfpz = DataToEntity.DataTableToEntity<ZFPZ>(SelectTable);
                    List<Budget> listb = new List<Budget>();
                    DataTable ys = await BusinessRule.Warning.Waring.GetZBInfo(djbh, org);
                    ys = DateString.Dateformat(ys);
                    listb = DataToEntity.DataTableToEntityList<Budget>(ys) as List<Budget>;
                    info.budgets = listb;
                    return Success(info, true);
                }
                else
                {
                    string json = await GetJavaPZInfo(djbh);
                    JObject j = JObject.Parse(json);
                    JObject data = JObject.Parse(j["data"].ToString());
                    _logger.Log(LogLevel.Info, Success(data).ToJson());
                    return Success(data);
                }
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }


        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetZFPZInfoByID(string id)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                ZFPZInfo info = new ZFPZInfo();
                DataTable SelectTable = await BusinessRule.Warning.Waring.GetZFPZInfobyid(id);
                SelectTable = DateString.Dateformat(SelectTable);
                info.zfpz = DataToEntity.DataTableToEntity<ZFPZ>(SelectTable);
                List<Budget> listb = new List<Budget>();
                DataTable ys = await BusinessRule.Warning.Waring.GetZBInfoID(id);
                ys = DateString.Dateformat(ys);
                listb = DataToEntity.DataTableToEntityList<Budget>(ys) as List<Budget>;
                info.budgets = listb;
                return Success(info, true);

                //else
                //{
                //    string json = await GetJavaPZInfo(djbh);
                //    JObject j = JObject.Parse(json);
                //    JObject data = JObject.Parse(j["data"].ToString());
                //    _logger.Log(LogLevel.Info, Success(data).ToJson());
                //    return Success(data);
                //}
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        #endregion

        #region  "财务报表"
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetFianceData(string org = "", string month = "", string endmonth = "", string sflh = "", string ss = "", string type = "1", string datatype = "1", string dwzt = "")
        {
            try
            {

                string orgs = await Getorg();
                if (orgs.Length == 12)
                {
                    orgs = orgs.Substring(0, 9);
                }
                _logger.Log(LogLevel.Info, "传入单位编码"+org);
                _logger.Log(LogLevel.Info, "调用返回单位编码"+orgs);
                if (string.IsNullOrEmpty(org))
                {
                    org = "";
                }
                if (!org.Contains(orgs))
                {
                    org = orgs;
                }
                _logger.Log(LogLevel.Info, "单位编码"+org);
                DataTable table = null;
                if (month == null || month == "")
                {
                    if (DateTime.Now.Day <= 12)
                    {
                        month = DateTime.Today.AddMonths(-2).ToString("yyyyMM");
                    }
                    else
                    {
                        month = DateTime.Today.AddMonths(-1).ToString("yyyyMM");
                    }
                }
                //if (endmonth == null || endmonth == "")
                //{
                endmonth = month;
               // }
                switch (type)
                {
                    case "1":

                        table = await BusinessRule.Warning.Waring.GetSZMXB(org, month, endmonth, sflh, ss, dwzt, datatype);
                        table = CompareDataTable.TableInsertRow(table, 5);
                        break;
                    case "2":

                        table = await BusinessRule.Warning.Waring.GetZWZQB(org, month, endmonth, sflh, ss, dwzt, datatype);
                        table = CompareDataTable.TableInsertRow(table, 5);
                        break;
                    case "3":

                        table = await BusinessRule.Warning.Waring.GetKMYEB(org, month, endmonth, sflh, ss, dwzt, datatype);
                        table = CompareDataTable.TableInsertRow(table, 5);
                        break;
                    case "4":

                        table = await BusinessRule.Warning.Waring.GetZCFZB(org, month, endmonth, sflh, ss, dwzt, datatype);
                        table = CompareDataTable.TableInsertRow(table, 5);
                        break;
                    case "5":

                        table = await BusinessRule.Warning.Waring.GetSYFPB(org, month, endmonth, sflh, ss, dwzt, datatype);
                        table = CompareDataTable.TableInsertRow(table, 5);
                        break;
                    case "6":

                        endmonth = month;

                        table = await BusinessRule.Warning.Waring.GetZCFZBCW(org, month, endmonth, sflh, ss, dwzt, datatype);
                        table = CompareDataTable.TableInsertRow(table, 4);
                        break;
                    case "7":



                        table = await BusinessRule.Warning.Waring.GetLRBCW(org, month, endmonth, sflh, ss, dwzt);
                        table = CompareDataTable.TableInsertRow(table, 4);
                        break;
                }
                JObject jb = new JObject();

                string json = DatasetToJson.DataToJson(table);
                jb = JObject.Parse(json);
                return Success(jb, true);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        #endregion
        #region "数据检查"
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> CheckData(string org = "", string month = "")
        {
            try
            {
                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                string orgs = await Getorg();
                if (orgs.Length == 12)
                {
                    orgs = orgs.Substring(0, 9);
                }
                if (!org.Contains(orgs))
                {
                    org = orgs;
                }
                if (month == null || month == "")
                {
                    month = DateTime.Today.ToString("yyyyMM");
                }

                DataTable dataTable = await BusinessRule.Warning.Waring.CheckData(month, org);
                string json = DatasetToJson.DataToJson(dataTable);
                JObject jb = JObject.Parse(json);
                return Success(jb, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        #endregion

        #region "第三方接口"
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetKMYEB(string orgcode = "", string month = "")
        {
            try
            {
                if (string.IsNullOrEmpty(orgcode))
                {
                    return Fail("请输入单位代码！");

                }
                if (string.IsNullOrEmpty(month))
                {
                    return Fail("请输入会计期间！");
                }
                DataTable table = await BusinessRule.Warning.U8Data.GetKmyeb(orgcode, month);
                return Success(table);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetZTDW(string year)
        {
            try
            {
                if (string.IsNullOrEmpty(year))
                {
                    year = DateTime.Today.Year + "";
                }
                DataTable table = await BusinessRule.Warning.U8Data.getZTDW(year);
                return Success(table);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        #endregion


        #region "地块"
        /// <summary>
        /// 获取单位属性
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetZCLB()
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);
                DataTable table = await BusinessRule.Warning.Waring.GetDicInfo("zclb");
                return Success(table, true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        /// <summary>
        ///地块分页接口
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetZC_DK([FromQuery] BusinessEntity.Assets.ZC_DKQuerry querry)
        {
            try
            {
                querry.UserID = GetUserId();
                querry.DepartID = await Getorg();
                // querry.DepartID = await GetDepId("contract_permission");
                _logger.Info(querry.DepartID);
                (IEnumerable<dynamic>, int) SelectTable = await BusinessRule.Assets.GetZC_DK(querry);
                dynamic sum = await BusinessRule.Assets.GetZC_DKsum(querry);
                //List<string> list = new List<string>();
                //foreach (dynamic item in SelectTable.Item1)
                //{
                //    string id = item.id;
                //    list.Add(id);
                //}

                //List<JavaApi.SPSDataItem> spitems = await JavaApi.GetSPStatusJavaAPI(querry.FormCode, GetUserAccount(), list, await GetICApiInfo());
                //foreach (dynamic item in SelectTable.Item1)
                //{
                //    string id = item.id;
                //    var spstatus = spitems.Where(ii => ii.businessId == id).FirstOrDefault();
                //    string status = "unknown";
                //    if (item.status == "-1")
                //    {
                //        status = "draft";

                //    }
                //    else if (item.status == "0")
                //    {
                //        status = "uncheck";

                //    }
                //    else if (item.status == "1")
                //    {
                //        status = "checking";

                //    }
                //    else if (item.status == "2")
                //    {
                //        status = "checked";

                //    }
                //    else if (item.status == "3")
                //    {
                //        status = "reject";

                //    }
                //    else if (item.status == "4")
                //    {
                //        status = "invalid";

                //    }
                //    else
                //    {
                //        status = "unfilled";
                //    }
                //    item.panguData = GetPanGudData(spstatus, status);
                //}

                Pagex pa = new Pagex();
                pa.records = SelectTable.Item1;
                pa.total = SelectTable.Item2;
                pa.sum = sum;
                //_logger.Log(LogLevel.Info, Success(pa).ToJson());
                //return Success(pa);

                _logger.Log(LogLevel.Info, Success(pa).ToJson());
                return Success(pa);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 保存、提交地块接口
        /// </summary>
        /// <param name="zc"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> SaveZC_DK([FromBody] BusinessEntity.Assets.DK zc)
        {
            try
            {
                //    HT_SubmitHT htsubmit = new HT_SubmitHT();
                //    htsubmit.businessNo = ht.fkhtxx.htbh;
                //    htsubmit.amount = ht.fkhtxx.htje.ToString();
                //    htsubmit.deptName = ht.fkhtxx.sqbm;
                //    htsubmit.content = ht.fkhtxx.htmc;
                //  await JavaApi.UploadFileJavaAPI(ht.fkhtxx.htbh, ht.File, await GetICApiInfo());

                if (string.IsNullOrEmpty(zc.dk.zt))
                {
                    zc.dk.zt = "1";
                }
                if (zc.dk.zt == "1")
                {
                    zc.dk.kymj = 0;
                    zc.dk.czmj = 0;
                    zc.dk.jzmj = 0;
                   
                    foreach (BusinessEntity.Assets.DKZC dk in zc.dkzc)
                    {
                        zc.dk.kymj += dk.kymj;
                        zc.dk.czmj += dk.tradearea;
                        zc.dk.jzmj += dk.jzmj;
                        
                        zc.dk.zcsl++;
                    }
                    //if (zc.dk.jzmj > 0)
                    //{
                    //    zc.dk.xzl = zc.dk.kymj / zc.dk.jzmj * 100;
                    //}
                    //else
                    //{
                    //    zc.dk.xzl = 0;
                    //}
                    if (string.IsNullOrEmpty(zc.dk.listid))
                    {
                        zc.dk.listid = DateTime.Now.ToString("yyyyMMddHHmmssfffff");
                        await BusinessRule.Assets.InsertZC_DK(zc.dk);
                    }
                    else
                    {
                        await BusinessRule.Assets.UpdateZC_DK(zc.dk);
                    }
                }
                else
                {
                    bool bsp = false;
                    JavaApi.SPLEnt spl = new JavaApi.SPLEnt();
                    spl.businessName = "地块管理";
                    spl.businessId = zc.dk.listid;
                    // spl.publicParamKey = "FEE_PROCESS";
                    spl.formCode = "";

                    JavaApi.SPLEnt.Auditdescription _description = new JavaApi.SPLEnt.Auditdescription() { businessNo = zc.dk.listid, amount = zc.dk.kymj.ToString(), content = zc.dk.dkmc, deptName = zc.dk.dwmc };
                    // spl.description = Newtonsoft.Json.JsonConvert.SerializeObject(htsubmit);
                    spl.description = _description.ToJson();
                    spl.additionInfoJson = Newtonsoft.Json.JsonConvert.SerializeObject(zc.dk);
                    spl.callbackUrl = "http://ic-xmzc/netapi/Assets/UpdateDKStatus";
                    spl.callbackInterface = "";

                    spl.callbackInterface = "/contract-rule/payment/purchase-audit/audit/${taskId}/" + zc.dk.listid + " ";




                    bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                    zc.dk.zt = "2";

                    //string url = BaseEditPower.GetSPDetailUrl(BaseEditPower.TableName.合同.ToString(), ht.fkhtxx.htbh);
                    // JavaApi.SPLEnt spl = new JavaApi.SPLEnt("FKHTsubmit", ht.fkhtxx.htbh, ht.File.formCode, Newtonsoft.Json.JsonConvert.SerializeObject(ht.fkhtxx), "http://ic-xmzc/netapi/HT/SubmitHT_FKHT");
                    //bsp = await JavaApi.startInstanceJavaAPI(spl, await GetICApiInfo());
                    if (!bsp)
                    {
                        zc.dk.zt = "1";
                        await BusinessRule.Assets.UpdateZC_DK(zc.dk);
                        return Fail("提交失败，启动工作流异常");
                    }
                    else
                    {
                        await BusinessRule.Assets.UpdateZC_DK(zc.dk);

                        //return Success("成功");
                    }
                }
                await BusinessRule.Assets.DeleteZC_DKZC(zc.dk.listid);
                foreach (BusinessEntity.Assets.DKZC dk in zc.dkzc)
                {
                    dk.dkid = zc.dk.listid;
                    dk.listid = DateTime.Now.ToString("yyyyMMddHHmmssfffff");
                    await BusinessRule.Assets.InsertZC_DKZC(dk);

                }
                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }



        /// <summary>
        /// 删除地块接口
        /// </summary>
        /// <param name="Listid"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> DeleteZC_DK(string Listid)
        {
            try
            {
                await BusinessRule.Assets.DeleteZC_DK(Listid);

                return Success("成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 地块获取详情接口
        /// </summary>
        /// <param name="listid"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetZC_DKCByID(string listid)
        {
            try
            {
                BusinessEntity.Assets.BackDK dk = new BusinessEntity.Assets.BackDK();
                DataTable dt = await BusinessRule.Assets.GetZC_DKByID(listid);
                DataTable table = await BusinessRule.Assets.GetZC_DKZCByID(listid);

                dk.dk = APICommond.DataToEntity.DataTableToEntity<BusinessEntity.Assets.ZC_K>(dt);
                List<Asset> list = APICommond.DataToEntity.DataTableToEntityList<Asset>(table) as List<Asset>;
                dk.dkzc = list;

                return Success(dk);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }

        }


        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetAssetsDK([FromQuery] AssetQuerry querry)
        {
            try
            {

                _logger.Log(LogLevel.Info, this.Url.Action() + this.Request.QueryString.Value);

                string orgs = await Getorg();
                if (orgs.Length == 12)
                {
                    orgs = orgs.Substring(0, 9);
                }
                if (string.IsNullOrEmpty(querry.org))
                {

                    querry.org = orgs;
                }

                if (!querry.org.Contains(orgs))
                {
                    querry.org = orgs;
                }


                if (string.IsNullOrEmpty(querry.xzls) || querry.xzls == "null")
                {
                    querry.xzls = "0";
                }

                if (string.IsNullOrEmpty(querry.xzle) || querry.xzle == "null")
                {
                    querry.xzle = "0";
                }
                _logger.Log(LogLevel.Info, querry.org);
                _logger.Log(LogLevel.Info, querry.cyjg);
                if (string.IsNullOrEmpty(querry.dwsx))
                {
                    querry.dwsx = querry.sxmc;
                }
                (DataTable, int) SelectTable = await BusinessRule.Warning.Waring.GetAssetsDK(querry.org, querry.type, querry.zcmc, querry.zcbm, querry.zclb, querry.zylx, querry.zcxz, querry.zt, querry.zkdm, querry.dwlx, querry.dwsx, querry.cyjg, Convert.ToDecimal(querry.xzls), Convert.ToDecimal(querry.xzle),querry.dkmc,querry.lbdm,querry.sxmc, querry.current, querry.size);
                DataTable dataTable = await BusinessRule.Warning.Waring.GetAssetsSumDK(querry.org, querry.type, querry.zcmc, querry.zcbm, querry.zclb, querry.zylx, querry.zcxz, querry.zt, querry.zkdm, querry.dwlx, querry.dwsx, querry.cyjg, querry.dkmc, querry.lbdm,querry.sxmc);
                DataTable dataTablex = await BusinessRule.Warning.Waring.GetAssetsDKX(querry.org, querry.type, querry.zcmc, querry.zcbm, querry.zclb, querry.zylx, querry.zcxz, querry.zt, querry.zkdm, querry.dwlx, querry.dwsx, querry.cyjg, Convert.ToDecimal(querry.xzls), Convert.ToDecimal(querry.xzle), querry.dkmc, querry.lbdm, querry.sxmc, querry.current, querry.size);

                _logger.Log(LogLevel.Info, querry.org + "yyyyyy");
                int count = SelectTable.Item2;
                decimal summj = 0;
                decimal sumktmj = 0;
                decimal sumyz = 0;
                decimal htsl = 0;
                decimal htje = 0;
                foreach (DataRow row in dataTable.Rows)
                {
                    htsl = Convert.ToDecimal(row["htsl"]);
                    htje = Convert.ToDecimal(row["htje"]);

                }
                foreach (DataRow row in dataTablex.Rows)
                {
                    if (querry.type == "1")
                    {
                        if (row["jzmj"] != DBNull.Value)
                        {
                            summj = summj + Convert.ToDecimal(row["jzmj"]);
                        }
                    }
                    else
                    {
                        if (row["zymj"] != DBNull.Value)
                        {
                            summj = summj + Convert.ToDecimal(row["zymj"]);
                        }
                    }
                    if (row["kymj"] != DBNull.Value)
                    {
                        sumktmj = sumktmj + Convert.ToDecimal(row["kymj"]);
                    }
                    if (row["yz"] != DBNull.Value)
                    {
                        sumyz = sumyz + Convert.ToDecimal(row["yz"]);
                    }
                  
                }
                decimal wyz = 0;
               
                AssetsSum sum = new AssetsSum();
                sum.count = count;
                sum.kymj = sumktmj;
                sum.total = count;
                sum.yz = sumyz;
                sum.zmj = summj;
                sum.htsl = htsl;
                sum.htje = htje;
                sum.wyz = wyz;
                sum.zyz = sumyz + wyz;
                List<Asset> list = new List<Asset>();
                list = DataToEntity.DataTableToEntityList<Asset>(SelectTable.Item1) as List<Asset>;
                sum.records = list;



                _logger.Log(LogLevel.Info, Success(sum).ToJson());
                return Success(sum);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Info, ex.Message);
                return Fail(ex.Message);
            }
        }
        #endregion


        #region "资产负债表导入"
        /// <summary>
        /// 下载四网导入模板
        /// </summary>
        /// <returns>文件流</returns>
        [HttpGet]
        [AllowAnonymous]
        public IActionResult Download()
        {

            try
            {
                string baseDir = ConfigHelper.GetValue<string>("baseDir");
                string filePath = baseDir + "/UpLoad/Template/四网导入模板.xls";
                return File(FileHelper.Read(filePath), "application/ms-excel", "资产负债表导入模板.xls");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
            //return response;
        }

        /// <summary>
        /// 导入 预览
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> ImportView([FromForm] IFormCollection formCollection)
        {
            try
            {
                string baseDir = ConfigHelper.GetValue<string>("baseDir");
                if (formCollection.Files.Count == 0)
                {
                    return Fail("请上传文件");
                }
                FormFileCollection filelist = (FormFileCollection)formCollection.Files;

                string nfilepath = "";
                foreach (IFormFile file in filelist)
                {
                    String Tpath = "/UpLoad/Files/";
                    string name = file.FileName;
                    string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string FilePath = baseDir + Tpath;

                    string type1 = Path.GetExtension(name);
                    DirectoryInfo di = new DirectoryInfo(FilePath);

                    if (!di.Exists)
                    {
                        di.Create();
                    }

                    using (FileStream fs = System.IO.File.Create(FilePath + FileName + type1))
                    {
                        // 复制文件
                        file.CopyTo(fs);
                        // 清空缓冲区数据
                        fs.Flush();
                    }
                    nfilepath = FilePath + FileName + type1;


                }
                string err = "";
                DataSet ds = APICommond.ImportExcel.GetExcelData(nfilepath, out err);
                if (err != "")
                {
                    return Fail(err);
                }
                string cols = "";

                for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                {

                    cols += ds.Tables[0].Columns[i].ColumnName.ToLower() + ",";

                }

                dynamic d = new ExpandoObject();
                d.cols = cols.TrimEnd(',');
                d.data = ds.Tables[0];
                return Success(d);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 导入
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Import([FromForm] IFormCollection formCollection)
        {
            try
            {
                string baseDir = ConfigHelper.GetValue<string>("baseDir");
                if (formCollection.Files.Count == 0)
                {
                    return Fail("请上传文件");
                }
                FormFileCollection filelist = (FormFileCollection)formCollection.Files;

                string nfilepath = "";
                string newfilename = "";
                foreach (IFormFile file in filelist)
                {
                    String Tpath = "/UpLoad/Files/";
                    string name = file.FileName;
                    string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string FilePath = baseDir + Tpath;

                    string type1 = Path.GetExtension(name);
                    DirectoryInfo di = new DirectoryInfo(FilePath);

                    if (!di.Exists)
                    {
                        di.Create();
                    }

                    using (FileStream fs = System.IO.File.Create(FilePath + FileName + type1))
                    {
                        // 复制文件
                        file.CopyTo(fs);
                        // 清空缓冲区数据
                        fs.Flush();
                    }
                    nfilepath = FilePath + FileName + type1;
                    newfilename = FileName + type1;

                }
                string err = "";
                DataSet ds = APICommond.ImportExcel.GetExcelData(nfilepath, out err);
                if (err != "")
                {
                    return Fail(err);
                }
                string kjqj = ds.Tables[0].Columns[0].ColumnName;
                _logger.Info("kjqj："+kjqj);
                kjqj = kjqj.Substring(kjqj.LastIndexOf("：") + 1);
                List<ZCFZBDR> list = new List<ZCFZBDR>();
                string org = "";
                string orgname = "";
                int index = 1;
                for (int i = 1; i < ds.Tables[0].Columns.Count; i++)
                {
                    if (i % 3 == 0)
                    {
                        int x = i / 3;

                        //string dw = ds.Tables[0].Rows[0][i-2].ToString();
                        if (i!=3)
                        {
                            if (ds.Tables[0].Rows[0][i - 2].ToString() == "")
                            {
                                break;
                            }
                        }
                        index = 1;
                        org = ds.Tables[0].Rows[0][i - 2].ToString();
                        orgname = ds.Tables[0].Rows[1][i - 2].ToString();

                        for (int j = 3; j < ds.Tables[0].Rows.Count; j++)
                        {

                            ZCFZBDR dr = new ZCFZBDR();
                            dr.kjqj = kjqj;
                            dr.drrq = DateTime.Today.ToString("yyyy-MM-dd");
                            DataRow row = ds.Tables[0].Rows[j];

                            dr.xm = row[0].ToString();
                            dr.xh = index;
                            dr.org = org;
                            dr.orgname = orgname;
                            dr.tcq = Convert.ToString(row[3 * x + 1 - 3]);
                            if (dr.tcq.Contains(","))
                            {
                                dr.tcq = dr.tcq.Replace(",", "");
                            }
                            if (dr.tcq.Replace("#VALUE!", "").Trim() == "")
                            {
                                dr.tcq = "0";
                            }

                            dr.tc = Convert.ToString(row[3 * x + 1 - 2]);
                            if (dr.tc.Contains(","))
                            {
                                dr.tc = dr.tc.Replace(",", "");
                            }
                            if (dr.tcq.Replace("#VALUE!", "").Trim() == "")
                            {
                                dr.tc = "0";
                            }
                            dr.tch = Convert.ToString(row[3 * x + 1 - 1]);
                            if (dr.tch.Contains(","))
                            {
                                dr.tch = dr.tch.Replace(",", "");
                            }
                            if (dr.tcq.Replace("#VALUE!", "").Trim() == "")
                            {
                                dr.tch = "0";
                            }
                            list.Add(dr);
                            index++;

                        }
                    }
                }

                //await BusinessRule.Warning.Waring.SaveFileDR();

                ImportFile fl = new ImportFile();
                fl.kjqj = kjqj;
                _logger.Info("org：" + org);
                if (org != "")
                {
                    fl.org = org.Substring(0, 9);
                }
               
                fl.filename = newfilename;
                await BusinessRule.Warning.Waring.SaveFileDR(fl);
                await BusinessRule.Warning.Waring.deleteDR(kjqj,org);
                await BusinessRule.Warning.Waring.SaveDR(list);
                //dynamic d = new ExpandoObject();
                //d.file = fl;
                //d.data =list;
                //DataTable table = await BusinessRule.Warning.Waring.GetZCFZBDR(org.Substring(0, 9), kjqj);
                //JObject jb = new JObject();

                //string json = DatasetToJson.DataToJson(table);
                //jb = JObject.Parse(json);
                //return Success(jb, true);
                JObject jb = new JObject();
                jb.Add("success", "成功");
                jb.Add("kjqj", kjqj.Substring(0, 4) + "-" + kjqj.Substring(4, 2));
                return Success(jb);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        ///  获取导入的文件列表
        /// </summary>
        /// <param name="org">单位编号</param>
        /// <param name="kjqj">会计期间</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> ImportFile(string org, string kjqj)
        {
            try
            {
                if (org.Length > 9)
                {
                    org = org.Substring(0, 9);
                }
                DataTable table = await BusinessRule.Warning.Waring.GetFiles(org, kjqj);
                return Success(table);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 下载指定文件
        /// </summary>
        /// <returns>文件流</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> DownloadImpFile(string org, string kjqj)
        {

            try
            {
                string orgs = await Getorg();
                _logger.Log(LogLevel.Info, "调用返回单位编码");
                if (string.IsNullOrEmpty(org))
                {
                    org = orgs;
                }
                if (org.Length > 9)
                {
                    org = org.Substring(0, 9);
                }
                if (kjqj.Contains("-"))
                {
                    kjqj = kjqj.Replace("-", "");
                }
                DataTable table = await BusinessRule.Warning.Waring.GetFiles(org, kjqj);
                string filename = "";
                if (table.Rows.Count > 0)
                {
                    filename = Convert.ToString(table.Rows[0]["filename"]).Trim();
                }
                else
                {
                    return Fail("选择的会计期间未导入文件！");
                }
                string baseDir = ConfigHelper.GetValue<string>("baseDir");
                string filePath = baseDir + "/UpLoad/Files/" + filename;
                return File(FileHelper.Read(filePath), "application/ms-excel", "资产负债表.xls");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
            //return response;
        }

        /// <summary>
        /// 查询导入的数据
        /// </summary>
        /// <param name="org">单位编号</param>
        /// <param name="kjqj">会计期间</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetImprotData(string org, string kjqj)
        {
            string orgs = await Getorg();
            _logger.Log(LogLevel.Info, "调用返回单位编码");
            _logger.Log(LogLevel.Info, "传入的org" + org);
            if (org == "undefined")
            {
                org = "";
            }
            _logger.Log(LogLevel.Info, "传入的org"+org);
            if (string.IsNullOrEmpty(org))
            {
                org = orgs;
            }
            if (string.IsNullOrEmpty(org))
            {
                return Fail("请选择单位！");
            }
            //if (org.Length > 9)
            //{
            //    org = org.Substring(0, 9);
            //}
            if (string.IsNullOrEmpty(kjqj))
            {
                DataTable data = await BusinessRule.Warning.Waring.GetMaxkjqj();
                if (data.Rows.Count == 0)
                {
                    return Fail("未导入过数据");
                }
                else
                {
                    kjqj = data.Rows[0]["kjqj"].ToString();
                }
            }
            if (kjqj.Contains("-"))
            {
                kjqj = kjqj.Replace("-", "");
            }
            DataTable table = await BusinessRule.Warning.Waring.GetZCFZBDR(org, kjqj);
            table.Columns.Remove("xh");
            //JObject jb = new JObject();

            //string json = DatasetToJson.DataToJson(table);
            //jb = JObject.Parse(json);
            dynamic d = new ExpandoObject();
            d.cols = DatasetToJson.GetDataCol(table);
            d.data = table;
            return Success(d, true);
        }

        /// <summary>
        /// 查询会计期间
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetKjqj()
        {

            DataTable table = await BusinessRule.Warning.Waring.Getkjqj();

            return Success(table);
        }
        #endregion
    }
}
